//导入数据库
const db=require('../db/index')
//导入bcryptjs
const bcrypt=require('bcryptjs')


exports.customerall= (req,res)=>{
    const sql='select * from customer'
    db.query(sql,(err,results)=>{
        if(err){ return res.cc(err)}
        res.json(results)
    })
}

exports.customerfind= (req,res)=>{
    var sql=` select * from customer ` 
    var info=req.body
    var type=info.selecttype
    if(info.inputtext.length!=0){
        var name=info.inputtext
        sql+=` where `
        if(type=='cust_name')
        {
            sql+=` cust_name like '%${name}%' `
        }else if(type=='cust_email')
        {
            sql+=` cust_email ='${name}' `
        }
    }
    console.log(sql)
    db.query(sql,(err,results)=>{
        if(err){ return res.cc(err)}
        res.json(results)
    })
}


exports.deletecustomer= (req,res)=>{
    const customerinfo=req.body
    const sql='delete from customer where cust_id=?'
    db.query(sql,customerinfo.id,(err,results)=>{
        if(err) return res.cc(err)
        if(results.affectedRows!=1)return res.cc('failed to delete')
        res.cc('delete successfully',0)
    })
}

exports.insertcustomer= (req,res)=>{
    const customerinfo=req.body
    const sql='select * from customer where cust_email=?'
    db.query(sql,customerinfo.email,(err,results)=>{
        if(err) return res.cc(err)
        if(results.length==1) res.cc('email address is exist,please change and try again')
        const sql='insert into customer set  ?'
        customerinfo.password=bcrypt.hashSync(customerinfo.password,10)
        db.query(sql,{cust_name:customerinfo.username,cust_password:customerinfo.password,cust_email:customerinfo.email,cust_idc:customerinfo.idc,cust_card_num:customerinfo.card},(err,results)=>{
        if(err) return res.cc(err)
        if(results.affectedRows!=1)return res.cc('failed to insert')
        res.cc('insert successfully',0)
    })
    })

    
}
exports.updatecustomer= (req,res)=>{
    const customerinfo=req.body
    const sql='update customer set ? where cust_id=?'
    db.query(sql,[{cust_name:customerinfo.username,cust_email:customerinfo.email,cust_idc:customerinfo.idc,cust_card_num:customerinfo.card},customerinfo.id],(err,results)=>{
        if(err) return res.cc(err)
        if(results.affectedRows!=1)return res.cc('failed to update')
        res.cc('update successfully',0)
    })
}
exports.resetcustomer= (req,res)=>{
    const customerinfo=req.body
    const sql='update customer set ? where cust_id=?'
      //encrypt
    customerinfo.password=bcrypt.hashSync(customerinfo.password,10)
    db.query(sql,[{cust_password:customerinfo.password},customerinfo.id],(err,results)=>{
        if(err) return res.cc(err)
        if(results.affectedRows!=1)return res.cc('failed to reset')
        res.cc('reset successfully',0)
    })
}
